'use strict';

const uidObj = require('uni-id');
const {
	Controller
} = require('uni-cloud-router');

module.exports = class IntegralController extends Controller {

	// 签到数据
	async signData() {
		let response = {
			code: 1,
			msg: '',
			datas: {}
		};

		let uid = '';
		let shop_id
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				shop_id = userRes.userInfo.shop_id
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		if (!shop_id) {
			response.msg = '门店id为空'
			return response;
		}
		const utc8date = this.service.utils.toDateUTC8(Date.now());
		// 当前第几周
		const weekDay = this.service.utils.getWeekDay(utc8date);

		// 获取签到数据
		const signRes = await this.db.collection('wmzmall-integral-sign')
			.where({
				is_delete: 0,
				member_uid: uid,
				sign_yy: utc8date.getFullYear(),
				sign_week_day: weekDay
			})
			.get();

		// 获取会员积分、已签到次数
		const memberSignRes = await this.db.collection('wmzmall-member')
			.field({
				member_integral: true,
				member_integral_sign_cnt: true,
				member_login_cnt: true
			})
			.where({
				_id: uid
			})
			.get();
		const memberSign = memberSignRes.data && memberSignRes.data[0];

		// 获取积分设置项
		const parameterRes = await this.db.collection('wmzmall-integral-parameter').where({
			shop_id: shop_id
		}).get();
		const parameter = parameterRes.data && parameterRes.data[0];

		response.datas = {
			signRes: signRes.data,
			memberSign,
			parameter,
			signData: {
				time: this.service.utils.formatdate(utc8date),
				week: "周" + "日一二三四五六".charAt(utc8date.getDay()),

				sign_in_full: parameter.continuous_sign_in_day,
				sign_in_full_integral: parameter.extra_gift_integral,
			}
		};
		response.code = 0;

		return response;
	}

	// 立即签到
	async signIn() {
		let response = {
			code: 1,
			msg: '',
			datas: {}
		};

		const utc8date = this.service.utils.toDateUTC8(Date.now());
		// 签到时间
		const signTime = this.service.utils.formatdate(utc8date, 'yyyy-MM-dd');

		const {
			addr,
			remark
		} = this.ctx.data;

		let uid = '';
		let uname = '';
		let shop_id
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				uname = userRes.userInfo.username || userRes.userInfo.nickname;
				shop_id = userRes.userInfo.shop_id
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		if (!shop_id) {
			response.msg = '门店ID为空'
			return response;
		}

		// 判断是否已签到
		const signed = await this.db.collection('wmzmall-integral-sign')
			.where({
				is_delete: 0,
				member_uid: uid,
				sign_time: signTime
			})
			.get();
		response.datas = signed;
		if (signed.data && signed.data.length > 0) {
			// 已签到
			response.msg = '今日已签到';
			return response;
		}

		// 当前第几周
		const weekDay = this.service.utils.getWeekDay(utc8date);
		// 获取积分设置项
		const parameterRes = await this.db.collection('wmzmall-integral-parameter').where({
			shop_id: shop_id
		}).get();
		const parameter = parameterRes.data && parameterRes.data[0];
		let integral = 0;
		if (parameter && parameter._id) {
			integral = parameter.everyday_sign_in_gain_integral;
		}
		let data = {
			member_id: uid,
			member_uid: uid,
			sign_time: signTime,
			sign_yy: utc8date.getFullYear(),
			sign_mm: utc8date.getMonth() + 1,
			sign_dd: utc8date.getDate(),
			sign_day: this.service.utils.getDayOfYear(utc8date),
			sign_week: "周" + "日一二三四五六".charAt(utc8date.getDay()),
			sign_week_day: weekDay,
			sign_integral: integral,
			sign_addr: addr,
			remark: remark,
			state: '已签到',
			is_delete: 0,
			time: this.service.utils.formatdate(utc8date, 'yyyy-MM-dd hh:mm'),
			create_time: Date.now(),
			create_uid: uid,
			create_uname: uname
		};
		const res = await this.db.collection('wmzmall-integral-sign').add(data);

		// 签到送积分
		if (res && res.id) {
			if (parameter && parameter._id) {
				if (parameter.everyday_sign_in_gain_integral > 0) {
					// 每天签到可获积分
					await this.service.integral.increase(uid, uname, {
						source: '签到',
						integral: parameter.everyday_sign_in_gain_integral
					});
				}

				// 连续签到满多少天
				if (parameter.continuous_sign_in_day > 0 && parameter.extra_gift_integral > 0) {

					// 判断是否已连续签到 continuous_sign_in_day 天
					const signedRes = await this.db.collection('wmzmall-integral-sign')
						.where({
							is_delete: 0,
							member_uid: uid,
							is_gift: 0
						})
						.orderBy('create_time', 'desc')
						.limit(parameter.continuous_sign_in_day)
						.get();

					if (signedRes.data && signedRes.data.length == parameter.continuous_sign_in_day) {
						let days = signedRes.data.map(x => x.create_time);
						// 判断是否连续签到
						if (this.service.utils.continueDays(days)) {
							// 额外赠送多少积分
							await this.service.integral.increase(uid, uname, {
								source: '签到赠送',
								integral: parameter.extra_gift_integral
							});

							const ids = signedRes.data.map(x => x._id);
							// 本次连续签到数据已赠送
							await this.db.collection('wmzmall-integral-sign')
								.where({
									_id: this.db.command.in(ids)
								}).update({
									is_gift: 1
								});
						}
					}
				}
			}

			response.msg = '签到成功';
		}

		response.datas = res;
		response.code = 0;

		return response;
	}

	// 积分数据
	async data() {

		let response = {
			code: 1,
			msg: '',
			datas: {}
		};

		let uid = '';
		let shop_id
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				shop_id=userRes.userInfo.shop_id
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		if (!shop_id) {
			response.msg = '门店ID为空'
			return response;
		}

		const memberRes = await this.db.collection('wmzmall-member').doc(uid)
			.field({
				member_integral: true,
				member_integral_sign_cnt: true,
				member_integral_use: true,
				member_integral_surplus: true,
				member_integral_total: true,
				is_plus: true,
				member_headimg: true,
				member_name: true,
				member_nickname: true
			}).get();
		let memberData = {};
		if (memberRes && memberRes.data.length === 1) {
			memberData = memberRes.data[0];
		}

		const categoryRes = await this.db.collection('wmzmall-integral-category')
			.where({
				shop_id:shop_id,
				is_delete: 0,
				state: '启用'
			})
			.orderBy('sort', 'asc')
			.get();

		response.datas = {
			member: memberData,
			categories: categoryRes.data
		};
		response.code = 0;
		return response;
	}

	// 积分商品详情
	async goodsDetail() {
		let response = {
			code: 1,
			goods: {},
			goods_detail: {},
			evaluate: [],
			evaluate_cnt: 0,
		};

		let start = new Date().getTime();
		const {
			goods_id,
			share_mid
		} = this.ctx.data;

		// 产品状态
		let goods_state = '';
		let goods = await this.db.collection('wmzmall-integral-goods').doc(goods_id).get();

		if (!goods || goods.data.length <= 0) {
			response.msg = `当前产品不存在`;
			return response;
		}
		goods_state = goods.data[0].state;
		if (goods_state != '销售中') {
			switch (goods_state) {
				case '待审核':
					response.msg = `当前产品未开售`;
					break;
				case '已下架':
					response.msg = `当前产品已下架`;
					break;
				default:
					response.msg = `当前产品${goods_state}`;
					break;
			}
			return response;
		}

		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {

			}
		}

		response.goods = goods.data[0];

		const detail = await this.db.collection('wmzmall-goods-detail')
			.where({
				goods_id
			})
			.get();
		const evaluate = await this.db.collection('wmzmall-integral-comment')
			.where({
				goods_id: goods_id,
				state: '显示'
			})
			.orderBy('create_time', 'desc')
			.limit(3)
			.get();
		const evaluateCountRes = await this.db.collection('wmzmall-integral-comment').where({
			goods_id: goods_id,
			state: '显示'
		}).count();
		if (evaluateCountRes && evaluateCountRes.total) {
			response.evaluate_cnt = evaluateCountRes.total;
			response.evaluate = evaluate.data;
		}

		if (detail.data && detail.data.length === 1) {
			response.goods_detail = detail.data[0];
		}

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 积分商品下单详情
	async goodsDetail2Order() {
		let start = new Date().getTime();
		let response = {
			code: 1
		};
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		// 请求参数
		const req = this.ctx.data;
		let {
			goods_id
		} = this.ctx.data;

		let goods = [];
		let goodsData = {};

		let goodsRes = {};

		if (goods_id) {
			// 从商品详情页下单
			goodsRes = await this.db.collection('wmzmall-integral-goods').doc(goods_id).get();

			if (!(goodsRes && goodsRes.data.length == 1)) {
				response.msg = '当前下单商品不存在';
				return response;
			}
			goodsData = goodsRes.data[0];
			let goodsState = goodsData.state;
			if (goodsState != '销售中') {
				switch (goodsState) {
					case '待审核':
						response.msg = `当前产品未开售`;
						break;
					case '已下架':
					default:
						response.msg = `当前产品${goodsState}`;
						break;
				}
				return response;
			}

			// 默认下单数量1
			goodsData.goods_num = 1;

			goods.push({
				goods: goodsData
			});
		}


		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.datas = goods;
		response.code = 0;
		response.msg = `获取成功`;
		return response;
	}

	// 积分下单
	async orderCreate() {
		// 判断是否登录
		// 判断收货人是否存在
		// 判断下单来源 (1.从商品详情下单)
		// 	判断商品是否存在
		// 	判断商品状态是否为 销售中
		// 	判断商品库存是否满足下单数
		// 写入订单详情数据
		// 记录会员下单积分数据
		// 扣减对应商品扣除
		// 写入订单日志

		let response = {
			code: 1,
			datas: {}
		};

		const start = new Date().getTime();
		const nowdate = start;

		let uid = '';
		let app_id
		let shop_id
		let user = {
			openid: '',
			name: '',
			headimg: '',
			mobile: ''
		};
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				app_id=userRes.userInfo.app_id
				shop_id=userRes.userInfo.shop_id
				if (userRes.userInfo.wx_openid) {
					user.openid = userRes.userInfo.wx_openid['mp-weixin'];
				}
				user.name = userRes.userInfo.username || userRes.userInfo.nickname;
				user.headimg = userRes.userInfo.avatar;
				user.mobile = userRes.userInfo.mobile || '';
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		if (!shop_id) {
			response.msg = '门店ID为空'
			return response;
		}

		const {
			sharemid,
			goods_id,
			goods_num,
			addr_id,
			order_from,
			order_desc
		} = this.ctx.data;

		const memberRes = await this.db.collection('wmzmall-member').doc(uid)
			.field({
				member_session_key: false,
				member_password: false
			}).get();

		let memberData = {};
		if (memberRes && memberRes.data.length === 1) {
			memberData = memberRes.data[0];
		}
		// 当前积分
		const integral = memberData.member_integral;

		const addrRes = await this.db.collection('wmzmall-member-address').doc(addr_id).get();
		if (!(addrRes && addrRes.data.length === 1)) {
			response.msg = '请选择收货人';
			return response;
		}
		const addr = addrRes.data[0];
		if (addr.create_uid != uid) {
			response.msg = '收货人与当前账号不一致';
			return response;
		}

		let goods = [];
		let goodsData = {};
		let preOrder = {};

		if (goods_id) {
			// 从商品详情页下单
			let goodsRes = await this.db.collection('wmzmall-integral-goods').doc(goods_id).get();
			if (!(goodsRes && goodsRes.data.length == 1)) {
				response.msg = '当前下单商品不存在';
				return response;
			}
			goodsData = goodsRes.data[0];
			let goodsState = goodsData.state;
			if (goodsState != '销售中') {
				switch (goodsState) {
					case '待审核':
						response.msg = `当前商品未开售`;
						break;
					case '已下架':
					default:
						response.msg = `当前商品${goodsState}`;
						break;
				}
				return response;
			}

			// 下单数量
			goodsData.goods_num = goods_num || 1;

			goods.push(goodsData);

			// 判断库存是否满足下单数
			if (goodsData.stock_num < goods_num) {
				response.msg = `当前商品库存数不足`;
				return response;
			}
		}

		if (goods.length <= 0) {
			response.msg = `下单商品不存在`;
			return response;
		}
		const utc8date = this.service.utils.toDateUTC8(Date.now());
		let order = {
			order_id: new Date().getTime() + (Math.round(Math.random() * 1000000) + '').padStart(6, '0'),
			order_member_openid: user.openid,
			order_member_name: user.name,
			order_member_headimg: user.headimg,
			order_member_mobile: user.mobile,
			order_consignee: addr.consignee,
			order_consignee_tel: addr.mobile,
			order_consignee_addr: addr.address,
			order_consignee_addr_detail: addr.addr_detail,
			order_consignee_province_name: addr.province_name,
			order_consignee_city_name: addr.city_name,
			order_consignee_district_name: addr.area_name,
			order_express: '',
			order_express_no: '',
			order_pay_no: new Date().getTime() + (Math.round(Math.random() * 1000000) + '').padStart(6,
				'0'),
			order_pay_way: '积分兑换',
			order_pay_state: '已付款',
			order_integral: 1,
			order_use_integral: 0,
			order_total_money: 0,
			order_total_cnt: goods.length,
			order_goods_cnt: 0,
			order_actural_paid: 0,
			order_from: order_from,
			order_type: '发货订单',
			order_way: '小程序',
			order_info: '',
			remark: order_desc,
			state: '待发货',
			yy_mm: this.service.utils.formatdate(utc8date, 'yyyy年MM月'),
			yy_mm_dd: this.service.utils.formatdate(utc8date, 'yyyy年MM月dd日'),
			is_delete: 0,
			create_uid: uid,
			create_time: nowdate,
			app_id:app_id,
			shop_id:shop_id
		};
		let order_detail = {};
		let order_details = [];
		goods.forEach(x => {
			order_detail = {
				order_id: order.order_id,
				goods_id: x._id,
				goods_name: x.name,
				goods_name_pw: x.name_pw,
				goods_img: x.img,
				goods_imgs: x.imgs,
				goods_num: x.goods_num,
				goods_integral: x.integral,
				goods_price: x.price,
				goods_type: x.goods_type || '',
				is_delete: 0,
				create_uid: uid,
				create_time: nowdate
			};

			order.order_goods_cnt += x.goods_num;
			order.order_total_money += x.integral * x.goods_num;
			order.order_actural_paid += x.integral * x.goods_num;
			order.order_info = x.name;

			order_details.push(order_detail);
		});

		// 判断当前积分是否可以兑换下单商品总积分
		if (order.order_actural_paid > integral) {
			response.msg = `当前积分不足`;
			return response;
		}

		// 开启事务
		const dbtran = await this.db.startTransaction();

		try {
			const orderRes = await dbtran.collection('wmzmall-integral-order').add(order);
			console.log('orderRes', orderRes);

			if (!(orderRes && orderRes.id)) {
				// 回滚事务
				await dbtran.rollback();

				response.msg = `订单创建失败`;
				uniCloud.logger.error(`订单创建失败`, order);
				console.log(`订单创建失败`, order);
				return response;
			}

			// 记录会员积分，事务模式
			await this.service.integral.decrease(uid, user.name, {
				integral: order.order_actural_paid,
				source: '积分兑换',
				order_id: order.order_id,
				goods_id,
			}, dbtran);

			// 判断积分是否大于等于0
			const memberIntegralRes = await dbtran.collection('wmzmall-member').doc(uid).field({
				member_integral: true
			}).get();

			if (memberIntegralRes.data.member_integral < 0) {
				await dbtran.rollback();
				response.msg = '当前可用积分不足';
				return response;
			}

			// 扣减商品库存
			const goods_num = order_details.find(x => x.goods_id == goods_id).goods_num;
			await dbtran.collection('wmzmall-integral-goods').doc(goods_id).update({
				stock_num: this.db.command.inc(-goods_num)
			});

			let order_log = {
				order_id: order.order_id,
				log_type: '创建订单',
				current_state: '待发货',
				prev_state: '待发货',
				ip: this.ctx.context.CLIENTIP,
				is_delete: 0,
				create_uid: uid,
				create_time: nowdate
			};

			await dbtran.collection('wmzmall-order-log').add(order_log);
			// 添加订单明细
			await this.db.collection('wmzmall-integral-order-detail').add(order_details[0]);

			// 提交事务
			await dbtran.commit();

			response.code = 0;
			response.datas = {
				order_id: order.order_id,
				money: order.order_actural_paid
			};

		} catch (e) {
			// 回滚事务
			await dbtran.rollback();

			response.code = 500;
			response.msg = e;

			// 记录日志
			uniCloud.logger.error(e);
			console.log('integral/orderCreate catch', e);
		}

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.msg = `耗时：${end - start}ms`;

		return response;
	}

	// 订单详情
	async orderDetail() {
		let response = {
			code: 1,
			order: {},
			order_detail: []
		};

		const start = new Date().getTime();
		const {
			order_id
		} = this.ctx.data;
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		const order = this.db.collection('wmzmall-integral-order').where({
			is_delete: 0,
			order_id: order_id,
			create_uid: uid
		}).get();
		const order_detail = this.db.collection('wmzmall-integral-order-detail').where({
			order_id: order_id
		}).get();
		const datas = await Promise.all([order, order_detail]);

		response.order = datas[0] && datas[0].data && datas[0].data[0];
		response.order_detail = datas[1] && datas[1].data;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 订单列表
	async orderList() {
		let response = {
			code: 1,
			order: []
		};

		const start = new Date().getTime();
		const {
			page,
			rows,
			state
		} = this.ctx.data;
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		let where_obj = {
			is_delete: 0,
			create_uid: uid
		};
		if (state && state != '全部') {
			where_obj.state = state;
		}

		let orderRes = await this.db.collection('wmzmall-integral-order')
			.where(where_obj)
			.orderBy('create_time', 'desc')
			.skip((page - 1) * rows)
			.limit(rows)
			.get();

		let datas = [];
		const ids = orderRes.data.map(x => x.order_id);

		let orderDetailsRes = await this.db.collection('wmzmall-integral-order-detail').where({
			order_id: this.db.command.in(ids)
		}).get();

		orderRes.data.forEach(x => {
			datas.push({
				order: x,
				order_detail: orderDetailsRes.data.filter(d => d.order_id == x.order_id)
			})
		});
		response.datas = datas;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	// 取消订单
	async orderCancel() {
		let response = {
			code: 1,
		};
		const start = new Date().getTime();
		const {
			order_id,
			state
		} = this.ctx.data;
		// console.log('this.ctx.data', this.ctx.data);
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		let where_obj = {
			create_uid: uid,
			order_id: order_id
		};

		let orderRes = await this.db.collection('wmzmall-integral-order')
			.where(where_obj)
			.update({
				state: state,

				last_modify_time: new Date().getTime(),
				last_modify_uid: uid,
			})

		if (orderRes && orderRes.updated == 1) {
			let order_log = {
				order_id: order_id,
				log_type: '取消订单',
				current_state: state,
				prev_state: '待付款',
				ip: this.ctx.context.CLIENTIP,
				is_delete: 0,
				create_uid: uid,
				create_time: new Date().getTime()
			};
			await this.db.collection('wmzmall-order-log').add(order_log);
		}

		response.datas = orderRes;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 已收货
	async orderReceived() {
		let response = {
			code: 1,
		};
		const start = new Date().getTime();
		const nowdate = start;

		const {
			order_id,
			state
		} = this.ctx.data;
		// console.log('this.ctx.data', this.ctx.data);
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}

		let where_obj = {
			is_delete: 0,
			create_uid: uid,
			order_id: order_id
		};

		let orderRes = await this.db.collection('wmzmall-integral-order')
			.where(where_obj)
			.field({
				order_actural_paid: true,
				order_id: true,
				is_fxs: true,
				is_settlement: true,
				order_fxs_uid: true,
				order_fxs_amount: true,
				order_member_name: true,
				order_member_openid: true,
				order_member_headimg: true,
				order_info: true,
				order_goods_cnt: true,
				create_uid: true,
			})
			.get();

		if (!(orderRes && orderRes.data && orderRes.data.length == 1)) {
			uniCloud.logger.info(`订单[${order_id}]不存在`);
			return response;
		}
		const order = orderRes.data[0];

		let orderUpdate = {
			state: state,

			last_modify_time: nowdate,
			last_modify_uid: uid
		};

		const orderUpdateRes = await this.db.collection('wmzmall-integral-order')
			.doc(order._id)
			.update(orderUpdate);

		if (orderUpdateRes && orderUpdateRes.updated == 1) {
			const order_log = {
				order_id: order_id,
				log_type: '已收货',
				current_state: state,
				prev_state: '待收货',
				ip: this.ctx.context.CLIENTIP,
				is_delete: 0,
				create_uid: uid,
				create_time: nowdate
			};
			await this.db.collection('wmzmall-order-log').add(order_log);
		}

		response.datas = orderUpdateRes;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 删除订单
	async orderDeleted() {
		let response = {
			code: 1,
		};
		const state = '已删除'
		const start = new Date().getTime();
		const {
			order_id,
		} = this.ctx.data;
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		let where_obj = {
			create_uid: uid,
			order_id: order_id,
			state: '已取消'
		};
		let orderRes = await this.db.collection('wmzmall-integral-order')
			.where(where_obj)
			.update({
				state: state,

				is_delete: 1,
				last_modify_time: new Date().getTime(),
				last_modify_uid: uid,
			})
			console.log(orderRes)
		if (orderRes && orderRes.updated == 1) {
			let order_log = {
				order_id: order_id,
				log_type: '删除订单',
				current_state: state,
				prev_state: '已取消',
				ip: this.ctx.context.CLIENTIP,
				is_delete: 0,
				create_uid: uid,
				create_time: new Date().getTime()
			};
			await this.db.collection('wmzmall-order-log').add(order_log);
		}

		response.datas = orderRes;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 物流轨迹
	async express() {
		let response = {
			code: 1,
			msg: '物流轨迹查询失败'
		};
		const {
			order_id
		} = this.ctx.data;
	
		if (!order_id) {
			response.msg = '订单号不存在';
			return response;
		}
	
		// 查询订单数据
		const orderRes = await this.db.collection('wmzmall-integral-order').where({
			order_id
		}).field({
			order_id: true,
			order_express: true,
			order_express_no: true,
			order_express_datas: true
		}).get();
	
		if (!orderRes || orderRes.data.length !== 1) {
			response.msg = '订单不存在';
			return response;
		}
	
		const order = orderRes.data[0];
	
		// 存在有数据直接返回 express datas
		if (order.order_express_datas) {
			response.msg = '数据查询成功';
			response.code = 0;
			response.datas = order.order_express_datas;
			response.datas.company = order.order_express;
	
			return response;
		}
	
		if (!order.order_express_no) {
			response.msg = '快递单号不存在';
	
			return response;
		}
	
		// 调用快递100 实时快递查询接口
		const kd100Res = await this.service.express.kd100Query({
			"com": this.service.express.getKd100Com(order.order_express),
			"num": order.order_express_no,
		});
		response.datas = kd100Res;
		response.msg = response.datas.message;
	
		if (response.datas && response.datas.message == "ok") {
			response.code = 0;
	
			/**
			 * 快递单状态
				0	在途	快件处于运输过程中
				1	揽收	快件已由快递公司揽收
				2	疑难	快递100无法解析的状态，或者是需要人工介入的状态， 比方说收件人电话错误。
				3	签收	正常签收
				4	退签	货物退回发货人并签收
				5	派件	货物正在进行派件
				6	退回	货物正处于返回发货人的途中
				7	转投	货物转给其他快递公司邮寄
				10	待清关	货物等待清关
				11	清关中	货物正在清关流程中
				12	已清关	货物已完成清关流程
				13	清关异常	货物在清关过程中出现异常
				14	拒签	收件人明确拒收
			 */
			if (['3', '4', '14'].includes(response.datas.state)) {
				response.datas.company = order.order_express;
				// 签收 退签 拒签
				// 写入订单物流轨迹数据
				await this.db.collection('wmzmall-integral-order').doc(order._id).update({
					order_express_datas: response.datas
				});
			}
		}
	
		return response;
	}
	
	// 订单评价
	async orderEvaluate() {
		let response = {
			code: 1
		};

		const start = new Date().getTime();
		const {
			order_id,
			review_cnt,
			review_imgs,
			review_type,
			review_content,
			review_anonymity
		} = this.ctx.data

		let uid = '';
		let app_id
		let shop_id
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				app_id=userRes.userInfo.app_id
				shop_id=userRes.userInfo.shop_id
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		let where_obj = {
			is_delete: 0,
			order_id: order_id,
			state: '待评价',
			create_uid: uid,
		};

		let orderRes = await this.db.collection('wmzmall-integral-order')
			.where(where_obj)
			.get();

		if (orderRes.data && orderRes.data.length == 1) {
			const orderDetailRes = await this.db.collection('wmzmall-integral-order-detail').where({
				order_id: order_id
			}).get();
			const order = orderRes.data[0];

			let order_log = {
				order_id: order_id,
				log_type: '评价订单',
				current_state: '已完成',
				prev_state: order.state,
				ip: this.ctx.context.CLIENTIP,
				is_delete: 0,
				create_uid: uid,
				create_time: new Date().getTime()
			};
			await this.db.collection('wmzmall-order-log').add(order_log);
			// 修改订单状态 已完成
			await this.db.collection('wmzmall-integral-order').doc(order._id).update({
				state: '已完成',

				last_modify_time: new Date().getTime(),
				last_modify_uid: uid
			});

			if (orderDetailRes.data) {
				let member_name = order.order_member_name;
				let member_headimg = order.order_member_headimg;
				if (review_anonymity) {
					// 脱敏处理
					member_name = this.service.utils.desz(order.order_member_name);
					member_headimg = '';
				}

				for (var i = 0; i < orderDetailRes.data.length; i++) {
					let x = orderDetailRes.data[i];
					await this.db.collection('wmzmall-integral-comment').add({
						goods_id: x.goods_id,
						goods_sku: x.goods_sku,
						goods_type: x.goods_type,
						member_name: member_name,
						member_headimg: member_headimg,
						order_id: order_id,
						review_type: review_type,
						review_cnt: review_cnt,
						review_content: review_content,
						review_imgs: review_imgs,
						review_anonymity: review_anonymity,
						remark: "",
						state: "显示",
						version: 1,
						is_delete: 0,
						create_uid: uid,
						create_time: new Date().getTime(),
						app_id:app_id,
						shop_id:shop_id
					});
				}
			}
		}

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.time = `耗时：${end - start}ms`;
		response.msg = '提交成功';
		return response;
	}
}
